﻿using System;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;

namespace Loong.Dapper.Uow
{
    public class ActiveTransactionInfo : IDisposable
    {
        private bool _disposed = false;
        private bool _isTransactionCommited = false;

        public DbConnection Connection { get; }

        public DbTransaction Transaction { get; }

        public ActiveTransactionInfo(DbConnection dbConnection, DbTransaction dbTransaction)
        {
            Connection = dbConnection;
            Transaction = dbTransaction;
        }

        public void Commit()
        {
            if (Transaction == null || _isTransactionCommited) return;

            Transaction.Commit();

            _isTransactionCommited = true;
        }

        public async Task CommitAsync()
        {
            if (Transaction == null || _isTransactionCommited) return;

            await Transaction.CommitAsync();

            _isTransactionCommited = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed) return;

            if (disposing)
            {
                if (Transaction != null)
                {
                    if (!_isTransactionCommited)
                    {
                        Transaction.Rollback();
                    }

                    Transaction.Dispose();
                }

                if (Connection != null)
                {
                    if (Connection.State == ConnectionState.Open)
                    {
                        Connection.Close();
                    }

                    Connection.Dispose();
                }
            }

            _disposed = true;
        }
    }
}
